<?php


namespace App\Repository;


use App\Contracts\IApi;
use App\Model\Repository\ApiProjectRepository;
use App\Model\Repository\ApiRepository;
use App\Model\Repository\ApiRequestBodyRepository;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

/**
 * Class Api
 * @package App\Repository
 */
class Api implements IApi
{
    /**
     * @param Request $request
     * @param ApiRepository $apiRepository
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function debug(Request $request, ApiRepository $apiRepository)
    {
        $presets = collect($apiRepository->project->preset()->get(['key', 'value', 'part'])->toArray())->groupBy('part')->toArray();
        $default_header = $presets['header'] ?? [];
        $default_body = $presets['body'] ?? [];
        $default_header = collect($default_header)->mapWithKeys(function ($item) {
            return [$item['key'] => $item['value']];
        })->all();
        $default_body = collect($default_body)->mapWithKeys(function ($item) use ($request) {
            return [$item['key'] => $item['key'] === 'loginToken' ? trim($request->post($item['key']), '"') : $request->post($item['key'])];
        })->all();
        $request_params = [];
        collect($apiRepository->request()->get())->map(function (ApiRequestBodyRepository $apiRequestBodyRepository) use ($request, &$request_params) {
            $param = $apiRequestBodyRepository->getParamName();
            switch ($apiRequestBodyRepository->getParamType()) {
                case 'int':
                    $request_params[$param] = (int)$request->post($param);
                    break;
                default:
                    $request_params[$param] = $request->post($param);
            }
        });
        $request_params = collect($default_body)->merge($request_params)->all();
        $client = new Client();
        $guzzle_params = [
            'headers' => $default_header,
            'form_params' => $request_params,
        ];
        if ($http_proxy = $request->post('http_proxy')) {
            $guzzle_params['proxy'] = $http_proxy;
        }
        $response = $client->request($apiRepository->getMethod(), $apiRepository->getRequestUrl(), $guzzle_params);
        return $response->getBody()->getContents();
    }
}
